import Vue from "vue";
import VueRouter from "vue-router";

import store from "@/store";

// 重写路由的 push 方法，解决重复跳转同一个地址，promise 报错问题
const originalPush = VueRouter.prototype.push;
/* 
  onComplete: 跳转成功处理函数(then)
  onAbort: 跳转失败处理函数(catch)
*/
VueRouter.prototype.push = function (
  location,
  onComplete = () => {},
  onAbort = () => {}
) {
  return originalPush.call(this, location, onComplete, onAbort);
};

Vue.use(VueRouter);

const Login = () => import("@pages/Login");
const Register = () => import("@pages/Register");
const Home = () => import("@pages/Home");
const Search = () => import("@pages/Search");
const Detail = () => import("@pages/Detail");
const AddCartSuccess = () => import("@pages/AddCartSuccess");
const ShopCart = () => import("@pages/ShopCart");
const Pay = () => import("@pages/Pay");
const PaySuccess = () => import("@pages/PaySuccess");
const Trade = () => import("@pages/Trade");
const Center = () => import("@pages/Center");

const MyOrder = () => import("@pages/Center/MyOrder");
const TeamOrder = () => import("@pages/Center/TeamOrder");

const router = new VueRouter({
  mode: "history",
  // 路由滚动
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  },
  routes: [
    {
      path: "/login",
      component: Login,
      name: "login",
      beforeEnter: (_, from, next) => {
        // 判断当前是否有 token (是否为登录状态)
        if (store.state.user.token) return next(from.path);
        next();
      },
    },
    { path: "/register", component: Register, name: "register" },
    { path: "/home", component: Home, name: "home" },
    { path: "/search/:keyword?", component: Search, name: "search" },
    { path: "/detail/:skuId?", component: Detail, name: "detail" },
    {
      path: "/addcartsuccess",
      component: AddCartSuccess,
      name: "addcartsuccess",
      beforeEnter: (_, __, next) => {
        // 判断 sessionStorage 中有没有，商品数据，如果有放行
        if (sessionStorage.getItem("AddCartSuccessShop")) return next();
        next("/shopcart");
      },
    },
    { path: "/shopcart", component: ShopCart, name: "shopcart" },
    {
      path: "/pay",
      component: Pay,
      name: "pay",
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/trade")) {
          next();
        } else {
          next("/shopcart");
        }
      },
    },
    {
      path: "/paysuccess",
      component: PaySuccess,
      name: "paysuccess",
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/pay")) {
          next();
        } else {
          next("/shopcart");
        }
      },
    },
    {
      path: "/trade",
      component: Trade,
      name: "trade",
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/shopcart")) {
          next();
        } else {
          next("/shopcart");
        }
      },
    },
    {
      path: "/center",
      component: Center,
      // name: "center",
      children: [
        { path: "myorder", component: MyOrder, name: "myorder" },
        { path: "teamorder", component: TeamOrder, name: "teamorder" },
        { path: "", redirect: "/center/myorder" },
      ],
    },
    { path: "/", redirect: "/home" },
  ],
});

router.beforeEach(async (to, __, next) => {
  /* 
    to: 即将要进入的目标路由
    from: 当前导航正要离开的路由
    next: 放行 
  */

  const { token } = store.state.user;

  // 首先判断是否拥有用户信息和 token (有代表是登录状态，直接放行)
  // if (token && userInfo) return next();

  // 判断当前路由是否需要 token (需要登录)
  const needAccessRoutes = ["/pay", "/paysuccess", "/trade", "/center"];
  // 只要 to 中的一级路由包含 needAccessRoutes 中的任何一个就需要 token (一真为真)
  const isAccess = needAccessRoutes.some((item) => {
    return to.path.startsWith(item);
  });
  if (isAccess) {
    // 该路由需要登录(先判断是否有 token 有的话代表它没有用户数据，重新请求用户数据并放行)
    if (token) {
      try {
        await store.dispatch("user/userInfoAction");
        return next();
      } catch (error) {
        alert("登录过期，请重新登录");
        localStorage.removeItem("USER_TOKEN");
        store.state.user.token = null;
        return next("/login");
      }
    }
    // 没有 token 铁定没登陆，直接放行到登录页
    alert("您未登录，请先登录哦！");
    next("/login");
  } else {
    // 该路由不需要登录，放行(如果有 token 就获取用户信息)
    if (token) {
      try {
        await store.dispatch("user/userInfoAction");
      } catch (error) {
        alert("登录过期，请重新登录！");
        localStorage.removeItem("USER_TOKEN");
        store.state.user.token = null;
        return next("/login");
      }
    }
    next();
  }
});

export default router;
